package com.acce.gxsc.page.reportForm.goodsForm;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.acce.gxsc.R;
import com.acce.gxsc.common.App;
import com.acce.gxsc.common.DateUtils;
import com.acce.gxsc.common.MyGridView;
import com.acce.gxsc.common.Tools;
import com.acce.gxsc.model.bean.ReportFormEvent;
import com.acce.gxsc.model.netBean.ReportFormBean;
import com.acce.sdk.BaseActivity;
import com.acce.sdk.User;
import com.acce.sdk.base.mvp.BaseMvpFragment;
import com.acce.sdk.widget.adapterlv.CommonAdapter;
import com.acce.sdk.widget.adapterlv.ViewHolder;
import com.acce.sdk.widget.stickygridheaders.StickyGridHeadersBaseAdapter;
import com.acce.sdk.widget.stickygridheaders.StickyGridHeadersGridView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by huxley on 2017/5/26.
 */
public class GoodsReportFormFragment extends BaseMvpFragment<GoodsReportFormView, GoodsReportFormPresenter> implements GoodsReportFormView {

    LayoutInflater       mInflater;
    List<ReportFormBean> mData;
    String               title;

    View rootView;
    @Bind(R.id.sgv)
    StickyGridHeadersGridView mSgv;
    MyStickyGridHeadersBaseAdapter mAdapter;
    @Bind(R.id.tv_time)
    TextView mTvTime;
    @Bind(R.id.tv_count)
    TextView mTvCount;

    public static GoodsReportFormFragment newInstance(String title) {
        Bundle args = new Bundle();
        args.putString("title", title);
        GoodsReportFormFragment fragment = new GoodsReportFormFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected GoodsReportFormPresenter createPresenter() {
        return new GoodsReportFormPresenter();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_goods_report_form, container, false);
        ButterKnife.bind(this, rootView);
        init();
        setHasOptionsMenu(true);
        EventBus.getDefault().register(this);
        return rootView;
    }

    private void init() {
        mInflater = LayoutInflater.from(getActivity());
        mData = new ArrayList<>();
        title = getArguments().getString("title");
        mAdapter = new MyStickyGridHeadersBaseAdapter();
        mSgv.setAdapter(mAdapter);
        mTvTime.setText(App.onTime);
    }

    int num = 0;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReportFormEvent(ReportFormEvent event) {
        num = event.num;
        mTvCount.setText(MessageFormat.format("总进场车辆：{0}车次", event.num));
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void showProgressDialog(String s, boolean b) {
        ((BaseActivity) getActivity()).showProgressDialog(s, b);
    }

    @Override
    public void hideProgressDialog() {
        ((BaseActivity) getActivity()).hideProgressDialog();
    }

    @Override
    public void printSuccess() {

    }

    public void load(ArrayList<ReportFormBean> reportFormBeen) {
        mData.clear();
        mData.addAll(reportFormBeen);
        mAdapter.notifyDataSetChanged();
    }

    @OnClick(R.id.btn_print)
    public void onClick() {
        ScrollView rootView = (ScrollView) mInflater.inflate(R.layout.dialog_report_form_info, (ViewGroup) getActivity().findViewById(R.id.dialog));
        final LinearLayout llContent = ButterKnife.findById(rootView, R.id.ll_content);
        final TextView tvOrderTitle = ButterKnife.findById(rootView, R.id.tv_order_title);
        final TextView tvClasses = ButterKnife.findById(rootView, R.id.tv_classes);
        final TextView tvCount = ButterKnife.findById(rootView, R.id.tv_count);
        final LinearLayout llChild = ButterKnife.findById(rootView, R.id.ll_child);
        final TextView tvTollCollector = ButterKnife.findById(rootView, R.id.tv_toll_collector);
        final TextView tvDate = ButterKnife.findById(rootView, R.id.tv_date);
        tvOrderTitle.setText(MessageFormat.format("交接班汇总报表({0})", title));
        tvClasses.setText(MessageFormat.format("班次：{0}", App.onTime));
        tvCount.setText(MessageFormat.format("总进场车辆：{0}车次", num));
        tvTollCollector.setText(MessageFormat.format("操作员：{0}", User.getInstance().getRealName()));
        tvDate.setText(DateUtils.getTime1());
//        llChild.setAdapter(mAdapter);
        for (int i = 0; i < mData.size(); i++) {
            LinearLayout view = (LinearLayout) mInflater.inflate(R.layout.item_dialog_report_form_info, llChild, false);
            TextView tvTitle = ButterKnife.findById(view, R.id.tv_title);
//            LinearLayout llItem = ButterKnife.findById(view, R.id.ll_item);
            MyGridView llItem = ButterKnife.findById(view, R.id.gv);
            ReportFormBean reportFormBean = mData.get(i);
            tvTitle.setText(reportFormBean.title);

            llItem.setAdapter(new CommonAdapter<String>(getContext(), R.layout.item_report_form_child, reportFormBean.contents) {
                @Override
                protected void convert(ViewHolder viewHolder, String s, int i) {
                    viewHolder.setText(R.id.tv_content, s);
                }
            });
//            for (int j = 0; j < reportFormBean.contents.size(); j++) {
//                String s = reportFormBean.contents.get(j);
//                RelativeLayout v1 = (RelativeLayout) mInflater.inflate(R.layout.item_report_form_child, llItem, false);
//                TextView tvContent = ButterKnife.findById(v1, R.id.tv_content);
//                tvContent.setText(s);
//                llItem.addView(v1);
//            }
            llChild.addView(view);
        }
        final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        final AlertDialog alertDialog = builder
                .setTitle("是否打印交接班汇总报表")
                .setView(rootView)
                .setNegativeButton("取消", null)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        mPresenter.printOrder(llContent);
                    }
                }).create();
        alertDialog.setCanceledOnTouchOutside(false);
        alertDialog.show();
    }


    //自定义adapter
    private class MyStickyGridHeadersBaseAdapter extends BaseAdapter implements StickyGridHeadersBaseAdapter {

        MyStickyGridHeadersBaseAdapter() {
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final ItemViewHolder ivh;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.item_report_form, parent, false);
                ivh = new ItemViewHolder();
                ivh.tvContent = (TextView) convertView.findViewById(R.id.tv_content);
                convertView.setTag(ivh);
            } else {
                ivh = (ItemViewHolder) convertView.getTag();
            }
            int group = 0;
            while (position >= mData.get(group).contents.size()) {
                position -= mData.get(group).contents.size();
                group++;
            }
            final String content = mData.get(group).contents.get(position);
            ivh.tvContent.setText(Tools.getStringNonNull(content));
            return convertView;
        }

        @Override
        public int getItemViewType(int position) {
            return 0;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public int getCount() {
            int count = 0;
            for (int i = 0; i < mData.size(); i++) {
                count += mData.get(i).contents.size();
            }
            return count;
        }

        @Override
        public int getNumHeaders() {
            return mData.size();
        }

        @Override
        public View getHeaderView(int position, View convertView, ViewGroup parent) {
            TabViewHolder tvh;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.item_report_form_title, parent, false);
                tvh = new TabViewHolder();
                tvh.tvTab = (TextView) convertView.findViewById(R.id.tv_title);
                convertView.setTag(tvh);
            } else {
                tvh = (TabViewHolder) convertView.getTag();
            }
            ReportFormBean saleSheet = mData.get(position);
            tvh.tvTab.setText(saleSheet.title);
            return convertView;
        }

        @Override
        public int getCountForHeader(int header) {
            return mData.get(header).contents.size();
        }

        class TabViewHolder {
            TextView tvTab;
        }

        class ItemViewHolder {
            TextView tvContent;
        }
    }
}
